//head
#include <STC15F2K60S2.H>
#include <iic.h>
#include <Led.h>
#include <ds18B20.h>
#include <Seg.h>
#include <init.h>
#include <Key.h>
#include <intrins.h>
//变量
unsigned char Key_Slow_Down,Key_Val,Key_Down,Key_Up,Key_Old;
unsigned char Seg_Slow_Down;
unsigned char Seg_Pos;
unsigned char Seg_Buf[8]={10,10,10,10,10,10,10,10};
unsigned char Seg_Point[8]={0,0,0,0,0,0,0,0};
unsigned char ucLed[8]={0,0,0,0,0,0,0,0};
float t;
char parameter=25;
unsigned char Seg_Mode=1;
float val=2.37;
bit Val_Mode;
//Key
void Key_Proc()
{
	if(Key_Slow_Down)return;
	Key_Slow_Down=1;
	
	Key_Val=Key_Read();
	Key_Down=Key_Val&(Key_Val^Key_Old);
	Key_Up=~Key_Val&(Key_Val^Key_Old);
	Key_Old=Key_Val;
	
	switch(Key_Down)
	{
		case 8:
			if(++Seg_Mode==4)Seg_Mode=1;
		break;
		case 9:
			if(Seg_Mode==2)
				parameter--;
		break;
		case 10:
			if(Seg_Mode==2)
				parameter++;
		break;
		case 11:
			Val_Mode^=1;
		break;
	}
	
}

//Seg
void Seg_Proc()
{
	if(Seg_Slow_Down)return;
	Seg_Slow_Down=1;
	/*信息获取区域*/
	t=rd_temperature();
	if(Val_Mode==0)
	{
		if(t<parameter)
			val=0;
		else
			val=5;
	}
	if(Val_Mode==1)
	{
		if(t<20)
			val=1;
		else
			val=t*0.15-2;
	}
	da_Write(val);
	
	/*数据显示区域*/
	//Seg_Point[5]=(Seg_Mode==1||Seg_Mode==3)?1:0;//        note 把小数点单独拎出来显示
	switch(Seg_Mode)
	{
		case 1:
			Seg_Buf[0]=12;
			Seg_Buf[4]=((unsigned char)t/10)?(unsigned char)t/10:10;
			Seg_Buf[5]=(unsigned char)t%10;                 //note  高位熄灭逻辑
			Seg_Point[5]=1;
			Seg_Buf[6]=(unsigned int)(t*10)%10;
			Seg_Buf[7]=(unsigned int)(t*100)%10;
		break;
		case 2:
			Seg_Buf[0]=13;
			Seg_Buf[4]=10;
			Seg_Buf[5]=10;
			Seg_Point[5]=0;
			Seg_Buf[6]=parameter/10;
			Seg_Buf[7]=parameter%10;
		break;
		case 3:
			Seg_Buf[0]=14;
			Seg_Buf[4]=10;
			Seg_Buf[5]=(unsigned char)val%10;
			Seg_Point[5]=1;
			Seg_Buf[6]=(unsigned int)(val*10)%10;
			Seg_Buf[7]=(unsigned int)(val*100)%10;
		
		break;
		
		
	}
	
}

//Led 
void Led_Proc()
{
	ucLed[0]=(Val_Mode)?0:1;
	ucLed[1]=(Seg_Mode==1)?1:0;
	ucLed[2]=(Seg_Mode==2)?1:0;
	ucLed[3]=(Seg_Mode==3)?1:0;
}

//T0
void Timer0_Init(void)		//1毫秒@12.000MHz
{
	AUXR |= 0x80;			//定时器时钟1T模式
	TMOD &= 0xF0;			//设置定时器模式
	TL0 = 0x20;				//设置定时初始值
	TH0 = 0xD1;				//设置定时初始值
	TF0 = 0;				//清除TF0标志
	TR0 = 1;				//定时器0开始计时
	ET0=1;
	EA=1;
}

void Timer0_Server()interrupt 1
{
	if(++Key_Slow_Down==10)Key_Slow_Down=0;
	if(++Seg_Slow_Down==200)Seg_Slow_Down=0;
	if(++Seg_Pos==8)Seg_Pos=0;
	Seg_Disp(Seg_Pos,Seg_Buf[Seg_Pos],Seg_Point[Seg_Pos]);
	Led_Disp(Seg_Pos,ucLed[Seg_Pos]);
}

void Delay750ms(void)	//@12.000MHz
{
	unsigned char data i, j, k;

	_nop_();
	_nop_();
	i = 35;
	j = 51;
	k = 182;
	do
	{
		do
		{
			while (--k);
		} while (--j);
	} while (--i);
}

void main()
{
	System_init();
	rd_temperature();
	Delay750ms();
	Timer0_Init();
	
	while(1)
	{
		
		Key_Proc();
		Seg_Proc();
		Led_Proc();
	}
}